<?php
/**
 * Display "Banishing Rules" creation popup
 * 
 * 
 */

use Fox\Html\CheckBox;
use Fox\Html\Input;
use Orx\Mailer\Messages;
use Orx\Mailer\MailBox\Message\Excluding\Rule;
use Fox\Popup;
use Fox\Html\Screen;

$xview = Xview::instance();
$inlineid = $xview->val('inlineid');

if(empty($inlineid)) {
	$rule = new Rule();
	$mode = 'create';
	$title = Msg(Messages::BUNDLE,Messages::CREATE_A_NEW_RULE_TO_BANISH_EMAILS);
} else {
	try {
		$mode = 'isave';
		$title = Msg(Messages::BUNDLE,Messages::EXCLUSION_RULE_HELP);
		$rule = Fox\Dao::load(Rule::className(), $inlineid);
	} catch (Fox\Object\Exception\NotExist $e) {
		// Should not happen
		\Fox\Message::Error($e);
	}
}
$data = $rule->getData();
$screen = new Screen('sRule',$mode,null,true);
$screen->message(Msg(Messages::BUNDLE,Messages::EXCLUSION_RULE_HELP));
$screen->block()
		->add(new Input('mail_from'))->parentObject()
		->add(new Input('mail_to'))->parentObject()
		->add(new Input(array('mail_subject','subject')))->parentObject()
		->add(new Input('included_words'))->parentObject()
		->add(new Input('excluded_words'))->parentObject()
		->add(new CheckBox(array('contains_attachement','has_attachement')));
$screen->initialize($data);
$screen->buttonBarClass('text-center');
if($screen->submitted()) {
	$fields = $screen->get();
	if(!$screen->errors()) {
		try {
			
			if($rule->exists()) {
				$rule->setFields($fields);
				$rule->update();
				Fox\Message::Success(Msg(Messages::BUNDLE,Messages::RULE_UPDATED));
			} else {
				$fields['idusr'] = User::current()->getId();
				$rule->setFields($fields);
				$rule->create();
				Fox\Message::Success(Msg(Messages::BUNDLE,Messages::RULE_CREATED));
			}
		} catch(Fox\Object\Exception\Save $e) {
			\Fox\Message::Error($e);
		}
	}
	return $xview->messages(true,true);
}
$popup = new Popup('pRules',$title,$screen,650);
return $popup->display(); 